﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Timers;
namespace TankServer.Core
{
    public class Conn
    {
        public Socket socket;
        public byte[] readBuffer;
        public bool isUse = false;
        public const int BUFFER_SIZE = 1024;
        public int buffcount = 0;

        //粘包分包
        public byte[] lenBytes = new byte[sizeof(Int32)];
        public Int32 msgLength = 0;
        public long lastTickTime = long.MinValue;
        public Player player;

        public Conn()
        {
            readBuffer = new byte[BUFFER_SIZE]; 
        }

        public void Init(Socket socket)
        {
            this.socket = socket;
            isUse = true;
            buffcount = 0;

            lastTickTime = Sys.GetTimeStamp();

        }


        public int BufferRemain()
        {
            return BUFFER_SIZE - buffcount;
        }

        public String GetAddress()
        {
            if (!isUse)
            {
                return "无法获取地址";
            }
            return socket.RemoteEndPoint.ToString();
        }

        public void Close()
        {
            if (!isUse) return;
            if (player != null)
            {
                return;
            }
            Console.WriteLine("[断开连接]"+GetAddress());
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            isUse = false;
        }

        public void Send(ProtocolBase protocol)
        {
            ServNet.instance.Send(this,protocol);
        }
    }
}
